import router from "@/router";
import store from "@/store";
import nprogress from "nprogress";
import "nprogress/nprogress.css";
import { asyncRoutes } from "@/router/index";

// 全局前置路由守卫
const whiteList = ["/login", "/404"];
router.beforeEach(async (to, from, next) => {
  // 开启进度条
  nprogress.start();
  const { token } = store.getters;
  if (token) {
    // 如果有 token 并且去的是登录页面，就跳到主页
    if (to.path === "/login") {
      // next(地址) 不会走路由后置守卫
      next("/");
      nprogress.done();
    } else {
      if (!store.getters.userid) {
        const { roles } = await store.dispatch("user/getUserInfo");
        const filterRoutes = asyncRoutes.filter((item) => {
          return roles.menus.includes(item.name);
        });
        store.commit("user/getRoutes", filterRoutes);
        // 添加路由的方法
        router.addRoutes([
          ...filterRoutes,
          { path: "*", redirect: "/404", hidden: true },
        ]);
        next(to.path); // 动态路由的已知缺陷，动态添加路由之后要调用next
      } else {
        next();
      }
    }
  } else {
    // 如果没有 token
    if (whiteList.includes(to.path)) {
      next();
    } else {
      next("/login");
      nprogress.done();
    }
  }
});

// 后置守卫
router.afterEach(() => {
  // 关闭进度条
  nprogress.done();
});
